package com.zues.samples.web;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zues.samples.model.PagerModel;
import com.zues.samples.model.User;
import com.zues.samples.service.UserService;
import com.zues.samples.service.modelVO.UserVO;
import com.zues.samples.util.ExcelUtils;

@Controller
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private LocaleResolver localeResolver;

	/**
	 * 列出UserList
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "listuser", method = RequestMethod.GET)
	public String users(Model model) throws Exception {
		model.addAttribute("user", new User());
		PagerModel<UserVO> list = userService.findAllByPage();
		model.addAttribute("userlist", list);
		return "teacher/userlists";
	}

	/**
	 * ADD页面
	 * 
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String toadd(RedirectAttributes redirectAttributes, @Validated User user, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			redirectAttributes.addAttribute("message", "添加失敗：生日格式错误");
			return "redirect:/listuser";
		}
		try {
			userService.createUser(user);
			redirectAttributes.addAttribute("message", "添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/listuser";
	}

	/**
	 * 通过ID查找到User 后 TO EDIT
	 * 
	 * @param model
	 * @param id
	 * @throws Exception
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> toedit(Model model, @PathVariable int id) throws Exception {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (id > 0) {
			User user = userService.getUserById(String.valueOf(id));
			modelMap.put("user", user);
			modelMap.put("success", true);
		} else {
			modelMap.put("success", false);
		}
		return modelMap;

	}

	/**
	 * 修改User
	 * 
	 * @param redirectAttributes
	 * @param user
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(RedirectAttributes redirectAttributes, User user, @PathVariable int id) {
		try {

			user.setUserID(String.valueOf(id));
			userService.editUser(user);
			redirectAttributes.addFlashAttribute("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/listuser";

	}

	/**
	 * 删除用户
	 * 
	 * @param redirectAttributes
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String delete(RedirectAttributes redirectAttributes, @PathVariable String id) {
		try {
			int ID = Integer.valueOf(id);
			userService.deleteUser(ID);
			redirectAttributes.addFlashAttribute("message", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/listuser";
	}

	/**
	 * 中英文切换
	 * 
	 * @param request
	 * @param response
	 * @param localType
	 * @return
	 */
	@RequestMapping(value = "/changeLocale")
	public String changeLocale(HttpServletRequest request, HttpServletResponse response, String LocaleType) {
		if ("en_US".equals(LocaleType)) {
			localeResolver.setLocale(request, response, Locale.US);
		} else {
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/listuser";
	}

	/**
	 * User批量文件上传
	 */
	@RequestMapping(value = "/uploadFile")
	public String uploadFile(@RequestParam(value = "uploadFile") MultipartFile[] uploadFile, HttpSession session,
			RedirectAttributes redirectAttributes) {
		// 获取单个文件
		MultipartFile uploadSimpleFile = uploadFile[0];

		String fileName = uploadSimpleFile.getOriginalFilename();

		String postfix = fileName.substring(fileName.lastIndexOf(".") + 1);

		try {
			if (ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix)
					|| ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
				userService.saveUserByExcel(uploadSimpleFile.getInputStream(), postfix);
			} else {
				redirectAttributes.addFlashAttribute("message", "文件格式不正确");
			}
		} catch (Exception e) {
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "批量导入失败");
		}
		return "redirect:/listuser";
	}
}
